package session01;

import javax.swing.*;
import java.sql.*;

public class TestPractise2 {
    public static void main(String[] args) {
        String name = JOptionPane.showInputDialog(null, "请输入用户名");
        String pwd = JOptionPane.showInputDialog(null, "请输入密码");
        String temp = JOptionPane.showInputDialog(null, "请输入余额");
        //将String转化为Double
        Double account = Double.parseDouble(temp);
        insert(name, pwd, account);
    }

    /**
     * 往数据库进行添加用户名，密码，余额
     *
     * @param name
     * @param pwd
     * @param account
     */
    private static void insert(String name, String pwd, Double account) {
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "123456";

        String sql = "insert into t_user(f_username,f_password,f_account) values (?,?,?)";
        try (Connection con = DriverManager.getConnection(url, user, password);
             PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            ps.setString(1, name);
            ps.setString(2, pwd);
            ps.setDouble(3, account);
            ps.executeUpdate();
            //获取新增数据的自动生成ID
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                int newID = rs.getInt(1);
                System.out.println(newID);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
